import React, { useContext } from 'react'

const ThemeContext = React.createContext({
  theme: 'light',
})

const MyContext = React.createContext({
  name: '默认用户',
  img: 'https://tva1.sinaimg.cn/large/e6c9d24egy1gzol5ragcfj20m80dw75d.jpg',
})

const Nav = () => {
  return (
    <>
      <h2>导航栏</h2>
      <UserAvatar />
      <UserLogin />
    </>
  )
}
class UserAvatar extends React.Component {
  static contextType = MyContext
  render() {
    console.log(this.context)
    return <img width={100} src={this.context.img} />
  }
}
class UserLogin extends React.Component {
  render() {
    return (
      <div>
        <ThemeContext.Consumer>
          {(theme) => (
            <MyContext.Consumer>
              {(user) => (
                <>
                  {user.name}
                  <button className={`btn btn-${theme.theme}`}>登出</button>
                </>
              )}
            </MyContext.Consumer>
          )}
        </ThemeContext.Consumer>
      </div>
    )
  }
}
const Content = () => {
  return (
    <>
      <h2>内容</h2>
      <Sidebar />
    </>
  )
}
const Sidebar = () => {
  return (
    <>
      <h2>侧边栏</h2>
      <UserStats />
    </>
  )
}
const UserStats = () => {
  const user = useContext(MyContext)
  const theme = useContext(ThemeContext)
  return <ul>{
    Object.keys(user).map(key => (
      <li key={key}>{key}:{user[key]}</li>
    ))
  }<li>当前主题: {theme.theme}</li></ul>
}

const ContextDemo = () => {
  const user = {
    name: '张三',
    level: 99,
    honor: 10273,
    img: 'https://tva1.sinaimg.cn/large/e6c9d24egy1gzolib9slrj215o0ltjuc.jpg',
  }
  const theme = { theme: 'primary' }
  return (<>
    <ThemeContext.Provider value={theme}>
      <MyContext.Provider value={user}>
        <Nav />
        <Content />
      </MyContext.Provider>
      <UserLogin />
    </ThemeContext.Provider>
    <UserLogin />
    <UserStats />
    </>
  )
}

export default ContextDemo
